﻿create PROCEDURE Sync.SP_BoardAttachments_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @BoardAttachments_Temp TABLE 
		(
			BoardAttachmentID UniqueIdentifier,
			[BoardID] uniqueidentifier,
				[Attachment] uniqueidentifier,
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @BoardAttachments_Temp 
	   SELECT	Tbl.Col.value('BoardAttachmentID[1]','uniqueidentifier') BoardAttachmentID,
                Tbl.Col.value('BoardID[1]', 'uniqueidentifier') [BoardID],
Tbl.Col.value('Attachment[1]', 'uniqueidentifier') [Attachment],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/BoardAttachments') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[BoardAttachments] ([BoardAttachmentID],[BoardID],[Attachment])
	SELECT t.[BoardAttachmentID],t.[BoardID],t.[Attachment]
	FROM  @BoardAttachments_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.BoardAttachments_Tracking s
        WHERE t.BoardAttachmentID = s.BoardAttachmentID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[BoardAttachments]
	SET [BoardAttachments].[BoardID] = t.[BoardID],[BoardAttachments].[Attachment] = t.[Attachment] 
	FROM [dbo].[BoardAttachments] s JOIN @BoardAttachments_Temp t 
    ON t.BoardAttachmentID = s.BoardAttachmentID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.BoardAttachments_Tracking r
				  WHERE t.BoardAttachmentID = r.BoardAttachmentID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[BoardAttachments]
    FROM @BoardAttachments_Temp t JOIN [dbo].[BoardAttachments] s
    ON t.BoardAttachmentID = s.BoardAttachmentID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END











